package ig.metrica.ui.modelo;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Collections;
import java.util.Hashtable;
import java.util.Iterator;

import javax.naming.NamingException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import javax.swing.table.AbstractTableModel;

import ig.finanzas.AccionPK;
import ig.metrica.origenesdedatos.OrigenDeDatosBean;
import ig.metrica.origenesdedatos.OrigenesdatosDTO;
import ig.metrica.ui.PantallaSevinproPanel;
import ig.metrica.ui.ServiceLocator;
import java.util.*;


public class PantallaDefinicionParametrosLiquidez extends PantallaSevinproPanel {
    
    private Hashtable comportamientoAcciones = new Hashtable();    
    private JTextField txtBanda1;
    private JComboBox comboAcciones;
    private JTextField txtNodias;
    private JButton btnAdicionar;
    private JScrollPane scroll;
    private JTable tabla;
    private JButton btnEliminar;

    private JComboBox[] comboBoxsColumns=new JComboBox[1];

    @Override
    public JComboBox[] getComboBoxsColumnsTable1() {
        return comboBoxsColumns;
    }

    private JComboBox[] comboBoxsColumnsTable2=new JComboBox[1];
    @Override
    public JComboBox[] getComboBoxsColumnsTable2() {
        return comboBoxsColumnsTable2;
    }

//    private OrigenDeDatos origenAcciones=null;
    
    public PantallaDefinicionParametrosLiquidez(PantallaDatosBasicosModelo datosbasicos,ThreadModelos threadModelos ) throws RemoteException, NamingException, ClassNotFoundException, SQLException, ExceptionEnConsulta, Exception{
        this.threadModelos = threadModelos;
        this.datosbasicos=datosbasicos;
        JPanel panelSuperior;
        JPanel panel;
        
        setLayout( new BorderLayout() );
        
        //int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty, int anchor, int fill, Insets insets, int ipadx, int ipady
        
        add( panelSuperior = new JPanel(), BorderLayout.CENTER );
        panelSuperior.setLayout( new GridBagLayout() );
        panelSuperior.setBorder( BorderFactory.createEmptyBorder(10, 10, 15, 10) );
        //-----------------------------------------------------------------------
        panelSuperior.add( new JLabel(), new GridBagConstraints(0, 0, 1, 1, 0.4, 0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0) );
        panelSuperior.add( new JLabel("Configuracion de Bandas"), new GridBagConstraints(1, 0, 1, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0) );
        panelSuperior.add( txtBanda1 = new JTextField(), new GridBagConstraints(1, 1, 1, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0) );
        panelSuperior.add( new JLabel("   "), new GridBagConstraints(1, 3, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0) );
        panelSuperior.add( panel = new JPanel(), new GridBagConstraints(1, 4, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0) );
        panel.setLayout( new GridBagLayout() );
        panel.setBorder( BorderFactory.createTitledBorder( BorderFactory.createLineBorder(Color.GRAY), "Configuracion de Liquidacion de Acciones", TitledBorder.LEADING, TitledBorder.TOP ) );
        //------------------------------------------------------------------
        panel.add( new JLabel("Accion"), new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0) );
        panel.add( new JLabel("No. Dias"), new GridBagConstraints(1, 0, 1, 1, 0.3, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0) );
        panel.add( comboAcciones = new JComboBox(), new GridBagConstraints(0, 1, 1, 1, 1, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0) );
        panel.add( txtNodias = new JTextField(5), new GridBagConstraints(1, 1, 1, 1, 0.3, 0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0) );
        panel.add( btnAdicionar = new JButton("Adicionar"), new GridBagConstraints(2, 0, 1, 2, 0.3, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
        panel.add( scroll = new JScrollPane( tabla = new JTable(new ModeloTablaPDPL(comportamientoAcciones)) ), new GridBagConstraints(0, 2, 2, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0) );
        scroll.setBorder( BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(10, 10, 10, 10), BorderFactory.createLineBorder(Color.GRAY) ) );
        panel.add( btnEliminar = new JButton("Eliminar"), new GridBagConstraints(2, 2, 1, 1, 0.3, 1, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0) );
        panelSuperior.add( new JLabel(), new GridBagConstraints(2, 0, 1, 1, 0.4, 0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0) );
        
        btnAdicionar.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){btnAdicionarActionPerformed(e);}});
        btnEliminar.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){btnEliminarActionPerformed(e);}});
        //------------------------------------------------------
        Integer id=0;
        //try {
            System.out.println("****** CARGANDO LAS ACCIONES *****");
            
            Collection ClibroCuentasProductos=new OrigenDeDatosBean().ejbFindByAll();
            ht.put("IDMODELO",threadModelos.getIdModelo());
            for (Object elem: ClibroCuentasProductos) {
                if(((OrigenesdatosDTO)elem).getEntidad().trim().equals("ACCIONES")){
                    id=((OrigenesdatosDTO)elem).getConsecutivo();
                    origenesdatsoOK.add(((OrigenesdatosDTO)elem));
                    //ArrayList datos = ((OrigenDeDatos)elem).obtenerDatos(ht);
                    
                    OrigenDeDatosBean origenDeDatosBean = new OrigenDeDatosBean();
                    origenDeDatosBean.setOrigenesdatosDTO((OrigenesdatosDTO)elem);
                    ArrayList datos = origenDeDatosBean.obtenerDatos(ht);
                    
                    int mapeoAccion = 0;//((OrigenDeDatos)elem).getArregloCampos().indexOf( "NOMBRE ACCION" );
                    Iterator i = datos.iterator();
                    while(i.hasNext()){
                        Object[] registro = (Object[])i.next();
                        AccionPK accionPK = new AccionPK( registro[mapeoAccion].toString().trim());
                        comboAcciones.addItem(accionPK);
                    }
                }
            }
//        } catch (Exception e) {
//            JOptionPane.showMessageDialog(threadModelos.panel,"No se pudo cargar las ACCIONES en la consulta con ID="+id+"\n"+e);
//            e.printStackTrace();
//            throw new ExceptionEnConsulta("Error tratando de Procesar las Acciones.\n"+e);
//        }
////
//        origenAcciones= ServiceLocator.getInstancia().getOrigenDatos("ACCIONES");
//        ht.put("IDMODELO",threadModelos.getIdModelo().toString());
//        Collection datos =null;
//        try {
//            datos =origenAcciones.obtenerDatos(ht);
//        } catch (SQLException e) {
//            throw new SQLException("Error: Origen de datos "+origenAcciones.getConsecutivo()+"\n\t["+e.getMessage()+"]");
//        }
//        int mapeoAccion = origenAcciones.getArregloCampos().indexOf( "NOMBRE ACCION" );
//        Iterator i = datos.iterator();
//        while(i.hasNext()){
//            Object[] registro = (Object[])i.next();
//            AccionPK accionPK = new AccionPK( (String)registro[mapeoAccion] );
//            comboAcciones.addItem(accionPK);
//        }
        tabla.getTableHeader().setReorderingAllowed(false);
    }
    
    public String getBanda1(){
        return txtBanda1.getText();
    }
    
    public void setBanda1(String banda1){
        txtBanda1.setText(banda1);
    }
    
    public Hashtable getComportamientoLiquidezAcciones(){
        return comportamientoAcciones;
    }
    
    public void setComportamientoLiquidezAcciones(Hashtable comportamiento){
        ((ModeloTablaPDPL)tabla.getModel()).setColeccion( comportamiento );
    }
    
    public void btnAdicionarActionPerformed(ActionEvent e){
        
        Object llave = comboAcciones.getSelectedItem();
        String texto = txtNodias.getText();
        if (texto!=null && !texto.trim().equals("") && !comportamientoAcciones.containsKey(llave) ){
            comportamientoAcciones.put( llave, new Integer(texto) );
            txtNodias.setText("");
            ((ModeloTablaPDPL)tabla.getModel()).setColeccion( comportamientoAcciones );
            ((AbstractTableModel)tabla.getModel()).fireTableDataChanged();
        }else{
            if (texto==null || texto.trim().equals("") )
                JOptionPane.showMessageDialog(this, "Especifique un valor para el numero de dias.");
            else if (comportamientoAcciones.containsKey(llave))
                JOptionPane.showMessageDialog(this, "El comportamiento para dicha accion ya se encuentra registrado");
        }
        
    }
    
    public void btnEliminarActionPerformed(ActionEvent e){
        
        int filaseleccionada = tabla.getSelectedRow();
        if (filaseleccionada!=-1){
            ArrayList lista = new ArrayList( comportamientoAcciones.keySet() );
            Collections.sort( lista );
            Object llave = lista.get( filaseleccionada );
            comportamientoAcciones.remove(llave);
            ((AbstractTableModel)tabla.getModel()).fireTableDataChanged();
        }else{
            JOptionPane.showMessageDialog(null, "Seleccione una fila.");
        }
    }
    
    public String getTitulo() {
        return  "Definicion Parametros Liquidez";
    }
    
    public void setModificable(boolean b) {
        txtBanda1.setEnabled(b);
        comboAcciones.setEnabled(b);
        txtNodias.setEnabled(b);
        btnAdicionar.setEnabled(b);
        tabla.setEnabled(b);
        btnEliminar.setEnabled(b);
    }
    
    public void limpiarCampos() throws Exception {
        txtBanda1.setText("");
        txtNodias.setText("");
        comportamientoAcciones = new Hashtable();
        ((ModeloTablaPDPL)tabla.getModel()).setColeccion( comportamientoAcciones );
    }
    
    Collection origenesdatsoOK=new ArrayList();
    public void salir() throws Exception {
        //this.origenAcciones.closePoolConnection();
        /*for (Object elem : origenesdatsoOK) {
            ((OrigenDeDatos)elem).closePoolConnection();
        }*/
    }
    public javax.swing.table.AbstractTableModel getClonModelTable_1() throws CloneNotSupportedException{
        return null;
    }

    public javax.swing.table.AbstractTableModel getClonModelTable_2() throws CloneNotSupportedException{
        return null;
    }

    public javax.swing.table.AbstractTableModel getClonModelTable_3() throws CloneNotSupportedException{
        return null;
    }

    @Override
    protected void eliminarLlaveEnTodasLasTablas(List<Object> keys) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
}
class ModeloTablaPDPL extends AbstractTableModel{
    
    private String[] titulos = { "Accion", "No. dias" };
    private Hashtable coleccion;
    
    public ModeloTablaPDPL(Hashtable coleccion){
        this.coleccion = coleccion;
    }
    
    public void setColeccion(Hashtable h){
        this.coleccion = h;
        fireTableDataChanged();
    }
    
    public String getColumnName(int col){
        return titulos[col];
    }
    
    public Class getColumnClass(int col){
        if (col==1)
            return Integer.class;
        
        return String.class;
    }
    
    public int getColumnCount(){
        return titulos.length;
    }
    
    public int getRowCount(){
        return coleccion.size();
    }
    
    public boolean isCellEditable(int row, int col){
        return false;
    }
    
    public void setValueAt(Object value, int row, int col){
        
    }
    
    public Object getValueAt(int row, int col){
        ArrayList lista = new ArrayList( coleccion.keySet() );
        Collections.sort( lista );
        Object llave = lista.get( row );
        
        if (col==0)
            return llave;
        
        return coleccion.get(llave);
        
    }
    
}
